<template>
  <view class="storage-test">
    <view class="title">存储状态测试页面</view>
    
    <!-- 基本信息部分 -->
    <view class="section">
      <text class="section-title">基本信息：</text>
      <view class="status-item">
        <text class="key">平台:</text>
        <text class="value">{{ storageStatus.platform || '未知' }}</text>
      </view>
      <view class="status-item">
        <text class="key">存储方式:</text>
        <text class="value">{{ storageStatus.method === 'plus' ? 'plus.storage' : 'uni.storage' }}</text>
      </view>
      <view class="status-item">
        <text class="key">plus.storage可用:</text>
        <text class="value">{{ storageStatus.plusAvailable ? '是' : '否' }}</text>
      </view>
      <view class="status-item">
        <text class="key">当前时间:</text>
        <text class="value">{{ formatTime(storageStatus.currentTime) }}</text>
      </view>
    </view>
    
    <!-- 存储状态部分 -->
    <view class="section">
      <text class="section-title">Token状态：</text>
      <view class="status-item">
        <text class="key">旧键名Token存在:</text>
        <text class="value">{{ storageStatus.hasOldToken ? '是' : '否' }}</text>
      </view>
      <view class="status-item">
        <text class="key">新键名Token存在:</text>
        <text class="value">{{ storageStatus.hasNewToken ? '是' : '否' }}</text>
      </view>
      <view class="status-item">
        <text class="key">Token总计存在:</text>
        <text class="value">{{ storageStatus.hasToken ? '是' : '否' }}</text>
      </view>
      <view class="status-item">
        <text class="key">是否过期:</text>
        <text class="value">{{ storageStatus.isExpired ? '是' : '否' }}</text>
      </view>
    </view>
    
    <!-- Token信息部分 -->
    <view class="section">
      <text class="section-title">Token详情：</text>
      <view class="token-info">
        <text>Token: {{ token || '无' }}</text>
        <text v-if="token">Token长度: {{ token.length }} 字符</text>
        <text>旧键名过期时间: {{ formatExpireTime(storageStatus.oldExpireTime) }}</text>
        <text>新键名过期时间: {{ formatExpireTime(storageStatus.newExpireTime) }}</text>
        <text v-if="storageStatus.expireTime">剩余时间: {{ getRemainingTime(storageStatus.expireTime) }}</text>
      </view>
    </view>
    
    <!-- 操作按钮组 -->
    <view class="button-group">
      <button @click="checkStorage" class="btn-primary">检查存储状态</button>
      <button @click="testSetToken" class="btn-secondary">设置测试Token</button>
      <button @click="testRemoveToken" class="btn-danger">删除Token</button>
      <button @click="testStorageAPI" class="btn-info">测试存储API</button>
      <button @click="migrateOldToken" class="btn-warning">迁移旧Token</button>
      <button @click="refreshToken" class="btn-success">刷新Token</button>
    </view>
    
    <!-- 操作日志部分 -->
    <view class="log-section">
      <text class="section-title">操作日志：</text>
      <scroll-view class="log-container" scroll-y>
        <view v-for="(log, index) in logs" :key="index" class="log-item">
          {{ log }}
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { checkStorageStatus, getToken, setToken, removeToken, initPlusStorage } from '@/utils/auth'

export default {
  data() {
    return {
      storageStatus: {},
      token: '',
      logs: []
    }
  },
  onLoad() {
    this.addLog('页面加载，开始检查存储状态')
    // 确保plus.storage已初始化
    initPlusStorage()
    this.checkStorage()
  },
  methods: {
    addLog(message) {
      const timestamp = new Date().toLocaleTimeString()
      this.logs.unshift(`[${timestamp}] ${message}`)
      if (this.logs.length > 30) {
        this.logs = this.logs.slice(0, 30)
      }
    },
    
    checkStorage() {
      try {
        this.addLog('开始检查存储状态...')
        
        // 确保plus.storage已初始化
        initPlusStorage()
        
        // 检查存储状态
        const status = checkStorageStatus()
        this.storageStatus = status
        this.addLog(`存储状态检查完成，使用存储方式: ${status.method === 'plus' ? 'plus.storage' : 'uni.storage'}`)
        this.addLog(`平台: ${status.platform}, plus.storage可用: ${status.plusAvailable}`)
        
        // 获取token信息
        const token = getToken()
        this.token = token
        this.addLog(`Token获取结果: ${token ? '成功' : '失败'}`)
        if (token) {
          this.addLog(`Token长度: ${token.length} 字符`)
        }
        
        // 记录新旧键名Token状态
        this.addLog(`旧键名Token存在: ${status.hasOldToken}, 新键名Token存在: ${status.hasNewToken}`)
        
        // 记录过期信息
        if (status.expireTime) {
          this.addLog(`过期检查: 过期时间=${this.formatExpireTime(status.expireTime)}, 是否过期=${status.isExpired}`)
          if (!status.isExpired) {
            this.addLog(`剩余时间: ${this.getRemainingTime(status.expireTime)}`)
          }
        } else {
          this.addLog('未设置过期时间')
        }
        
        this.addLog('存储检查完成')
      } catch (error) {
        this.addLog(`检查存储状态失败: ${error.message || error}`)
        console.error('检查存储状态失败:', error)
      }
    },
    
    testSetToken() {
      try {
        this.addLog('开始设置测试Token...')
        const testToken = 'test_token_' + Date.now()
        // 确保plus.storage已初始化
        initPlusStorage()
        const result = setToken(testToken, 7) // 7天过期
        this.addLog(`设置Token结果: ${result ? '成功' : '失败'}`)
        
        if (result) {
          this.addLog('测试Token设置完成，有效期7天')
          this.checkStorage()
        }
      } catch (error) {
        this.addLog(`设置Token失败: ${error.message || error}`)
        console.error('设置Token失败:', error)
      }
    },
    
    testRemoveToken() {
      try {
        this.addLog('开始删除Token...')
        // 确保plus.storage已初始化
        initPlusStorage()
        const result = removeToken()
        this.addLog(`Token删除${result ? '完成' : '失败'}`)
        if (result) {
          this.checkStorage()
        }
      } catch (error) {
        this.addLog(`删除Token失败: ${error.message || error}`)
        console.error('删除Token失败:', error)
      }
    },
    
    testStorageAPI() {
      try {
        this.addLog('开始测试存储API...')
        
        // 确保plus.storage已初始化
        initPlusStorage()
        
        // 测试不同的存储方式
        const testKey = 'storage_test_key'
        const testValue = 'test_value_' + Date.now()
        
        // 测试uni.setStorageSync
        uni.setStorageSync(testKey, testValue)
        const uniValue = uni.getStorageSync(testKey)
        this.addLog(`uni.storage测试: 设置=${testValue}, 获取=${uniValue}, 结果=${uniValue === testValue ? '成功' : '失败'}`)
        uni.removeStorageSync(testKey)
        
        // 测试plus.storage（如果在APP环境）
        if (typeof plus !== 'undefined' && plus.storage) {
          plus.storage.setItem(testKey, testValue)
          const plusValue = plus.storage.getItem(testKey)
          this.addLog(`plus.storage测试: 设置=${testValue}, 获取=${plusValue}, 结果=${plusValue === testValue ? '成功' : '失败'}`)
          plus.storage.removeItem(testKey)
        } else {
          this.addLog('plus.storage不可用')
        }
        
        this.addLog('存储API测试完成')
      } catch (error) {
        this.addLog(`测试存储API失败: ${error.message || error}`)
        console.error('测试存储API失败:', error)
      }
    },
    
    // 迁移旧Token到新键名
    migrateOldToken() {
      try {
        this.addLog('尝试迁移旧Token...')
        // 确保plus.storage已初始化
        initPlusStorage()
        
        // 调用checkStorageStatus会自动迁移旧Token
        const status = checkStorageStatus()
        this.addLog(`迁移完成，新键名Token存在: ${status.hasNewToken}`)
        this.checkStorage()
      } catch (error) {
        this.addLog(`Token迁移失败: ${error.message || error}`)
        console.error('Token迁移失败:', error)
      }
    },
    
    // 刷新Token（重新存储当前Token）
    refreshToken() {
      try {
        this.addLog('开始刷新Token...')
        // 确保plus.storage已初始化
        initPlusStorage()
        
        const currentToken = getToken()
        if (!currentToken) {
          this.addLog('当前没有Token可刷新')
          return
        }
        
        const result = setToken(currentToken, 7) // 7天过期
        this.addLog(`Token刷新结果: ${result ? '成功' : '失败'}`)
        if (result) {
          this.addLog('Token刷新完成，有效期7天')
          this.checkStorage()
        }
      } catch (error) {
        this.addLog(`刷新Token失败: ${error.message || error}`)
        console.error('刷新Token失败:', error)
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '未知'
      try {
        return new Date(timestamp).toLocaleString()
      } catch (error) {
        return '无效时间'
      }
    },
    
    // 格式化过期时间
    formatExpireTime(expireTime) {
      if (!expireTime) return '无'
      try {
        return new Date(parseInt(expireTime)).toLocaleString()
      } catch (error) {
        return '无效时间'
      }
    },
    
    // 计算剩余时间
    getRemainingTime(expireTime) {
      if (!expireTime) return '无'
      try {
        const currentTime = new Date().getTime()
        const expireMs = parseInt(expireTime)
        const timeDiff = expireMs - currentTime
        
        if (timeDiff <= 0) return '已过期'
        
        const hours = Math.floor(timeDiff / (1000 * 60 * 60))
        const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60))
        
        if (hours > 0) {
          return `${hours}小时 ${minutes}分钟`
        } else {
          return `${minutes}分钟`
        }
      } catch (error) {
        return '计算错误'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.storage-test {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
  color: #333;
}

.section {
  background: white;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 15rpx;
  display: block;
  border-left: 6rpx solid #007aff;
  padding-left: 15rpx;
}

.status-item {
  display: flex;
  justify-content: space-between;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #eee;
  
  &:last-child {
    border-bottom: none;
  }
}

.key {
  color: #666;
  font-size: 26rpx;
  min-width: 180rpx;
}

.value {
  color: #333;
  font-size: 26rpx;
  font-weight: 500;
  text-align: right;
  flex: 1;
}

.token-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  
  text {
    font-size: 26rpx;
    color: #333;
    word-break: break-all;
    padding: 5rpx 0;
  }
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  margin-bottom: 20rpx;
  padding: 10rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  
  button {
    flex: 1;
    min-width: 45%;
    padding: 20rpx;
    font-size: 26rpx;
    border-radius: 8rpx;
    border: none;
    color: white;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &.btn-primary {
      background-color: #007aff;
      
      &:active {
        background-color: #0056b3;
      }
    }
    
    &.btn-secondary {
      background-color: #5ac8fa;
      
      &:active {
        background-color: #38a4d6;
      }
    }
    
    &.btn-danger {
      background-color: #ff3b30;
      
      &:active {
        background-color: #cc2e25;
      }
    }
    
    &.btn-info {
      background-color: #5856d6;
      
      &:active {
        background-color: #403eaf;
      }
    }
    
    &.btn-warning {
      background-color: #ff9500;
      
      &:active {
        background-color: #cc7700;
      }
    }
    
    &.btn-success {
      background-color: #34c759;
      
      &:active {
        background-color: #28a745;
      }
    }
  }
}

.log-section {
  background: white;
  border-radius: 10rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.log-container {
  max-height: 400rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 15rpx;
  margin-top: 15rpx;
}

.log-item {
  font-size: 24rpx;
  color: #666;
  padding: 5rpx 0;
  border-bottom: 1rpx solid #eee;
  font-family: monospace;
  
  &:last-child {
    border-bottom: none;
  }
}
</style>